<?php
session_start();
require_once '../utils/validUtils.php';
require_once '../utils/Response.php';
require_once '../config/dbConfig.php';
global $conn;
connectDB();

$username = $_POST['username'];
$password = $_POST['password'];
$errors = [];

if (!validate_username($username)) {
    $errors['username'] = '用户名必须以字母开头';
}

if (!validate_password($password)) {
    $errors['password'] = '密码长度必须在6-8个字符之间';
}

if (!empty($errors)) {
    Response::error('验证失败', $errors)->send();
}

// 检查用户名是否已存在
$check = $conn->prepare("SELECT username FROM user WHERE username = ?");
$check->bind_param("s", $username);
$check->execute();
$result = $check->get_result();

if ($result->num_rows > 0) {
    Response::error('用户名已存在', ['username' => '用户名已存在'])->send();
}
$check->close();

// 插入新用户
$insert = $conn->prepare("INSERT INTO user (username, password) VALUES (?, ?)");
$insert->bind_param("ss", $username, $password);

if ($insert->execute()) {
    Response::success('注册成功')->send();
} else {
    Response::error('注册失败', ['database' => '注册失败，请稍后重试'])->send();
}

$insert->close();
$conn->close(); 